from django.contrib import auth
from django.http import HttpResponseRedirect
from django.template import RequestContext
from soup.portal.forms import LoginForm

class LoginLogoutMiddleware(object):
    # authenticates user and sets session
    
    def process_request(self, request):
        if request.POST:
            if request.POST.has_key("do_login"):
                # if login form was posted
                username = request.POST["username"]
                password = request.POST["password"]
                form_data = {"username":username, "password":password}
                form = LoginForm(form_data)
                # try to authenticate
                user = auth.authenticate(username=username, password=password)
                if form.is_valid() and user is not None and user.is_active:
                    # valid form && correct password && user is marked as active
                    auth.login(request, user)
                    request.user = user
                else:
                    # error occured, go back to login
                    request.session["login_error"] = True
                    return HttpResponseRedirect("/portal/login/?next=%s" % request.path)
            elif request.POST.has_key("do_logout"):
                # if logout form was posted
                auth.logout(request)
        return None